package com.tyc.wx.utills;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tyc.wx.model.WxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: java类作用描述
 * @Author: tyc
 * @CreateDate: 2020/12/29 15:23
 */
public class AppUtill {

    private WxProperties wxProperties;

    public AppUtill(WxProperties wxProperties) {
        this.wxProperties = wxProperties;
    }

    //通过code获取openid,sessionkey等信息
    public JSONObject getByCode(String code){
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String, String> requestUrlParam = new HashMap<>();
            //小程序appId
            requestUrlParam.put("appid",wxProperties.getMini_appid());
            //小程序secret
            requestUrlParam.put("secret", wxProperties.getMini_secret());
            //小程序端返回的code
            requestUrlParam.put("js_code", code);
            //默认参数
            requestUrlParam.put("grant_type", "authorization_code");
            //发送post请求读取调用微信接口获取openid用户唯一标识
            JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
            return jsonObject;
    }

    //获取电话号
    public JSONObject getPhone( String encryptedData,String session_key, String  iv){
        String result = WxDecodeUtils.wxDecrypt(encryptedData, session_key, iv);
        return  JSONObject.parseObject(result);
    }

    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=client_credential&appid=" + wxProperties.getMini_appid()
                + "&secret=" + wxProperties.getMini_secret();
        String result = HttpClientUtil.doGet(url,null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }

    /**
     * @param access_token 小程序access_token
     * @param message 模板消息
     * @return
     */
    public boolean sendTemplateMessage(String access_token,String message){
        String url =wxProperties.getMini__template_messageUrl();
        url = url.replace("ACCESS_TOKEN",access_token);
        String result1 = HttpClientUtil.doPostJson(url,message);
        JSONObject wxResult = JSONObject.parseObject(result1);
        String wxMessage = (String) wxResult.get("errmsg");
        if(wxMessage.equals("ok")){
            return true;
        }else {
            return false;
        }
    }
}
